class SOCK_Connector {

public:
	SOCK_Connector () : handle_(INVALID_SOCKET) {}

	// Initialize a passive-mode acceptor socket
	SOCK_Connector (INET_Addr &addr) 
	{
		open(addr);	
	}

	// A second method to initialize a passive-mode
	// acceptor socket, analogously to the constructor
	void open (INET_Addr &sock_addr) 
	{	
		sock_addr_ = sock_addr;
		// Create a local endpoint of communication
		handle_ = socket (PF_INET, SOCK_STREAM, 0);
		// Associate address with endpoint
		bind (handle_, sock_addr_.addr(), sock_addr_.size());
	}

	int connecting (SOCK_Stream &s, bool noBlock)
	{
		BOOL result = TRUE;
		// Connect to server.

		if (noBlock)
		{
			/* Not working....
			DWORD numBytes = 0;
			GUID guid = WSAID_CONNECTEX;
			LPFN_CONNECTEX ConnectExPtr = NULL;
			OVERLAPPED overlapped;
			memset(&overlapped, 0, sizeof(overlapped));
			int sucess = ::WSAIoctl(handle_, SIO_GET_EXTENSION_FUNCTION_POINTER, 
				(void*)&guid, sizeof(guid), (void *)&ConnectExPtr, sizeof(ConnectExPtr),
				&numBytes, NULL, NULL);

			if (ConnectExPtr == NULL || sucess != 0)
			{
				closesocket(handle_);
				handle_ = INVALID_SOCKET;
			}
			SOCKADDR addr = *sock_addr_.addr();
			result = ConnectExPtr(handle_, &addr, sizeof(addr), NULL, 0, NULL, &overlapped);
			if (result == FALSE)
			{
		    	printf("!ConnectEx error: %ld.\n", WSAGetLastError());
    			Sleep(2000);
			}
			*/ 
			u_long nNoBlock = 1;
			ioctlsocket(handle_, FIONBIO, &nNoBlock);
			int iResult = connect( handle_, sock_addr_.addr(), sock_addr_.size());
			if (iResult == SOCKET_ERROR) {
				if (WSAGetLastError() != WSAEWOULDBLOCK)
				{
					closesocket(handle_);
					handle_ = INVALID_SOCKET;
					result = FALSE;
				}
			}
			s.set_handle(handle_);

		}
		else
			connecting(s);

		if (result == TRUE)
			return 0;
		else
			return -1;

		// Should really try the next address returned by getaddrinfo
		// if the connect call failed
		// But for this simple example we just free the resources
		// returned by getaddrinfo and print an error message
		//freeaddrinfo(result);
	}

	void connecting (SOCK_Stream &s)
	{
		// Connect to server.
		int iResult = connect( handle_, sock_addr_.addr(), sock_addr_.size());
		if (iResult == SOCKET_ERROR) {
			closesocket(handle_);
			handle_ = INVALID_SOCKET;
		}
		s.set_handle(handle_);

		// Should really try the next address returned by getaddrinfo
		// if the connect call failed
		// But for this simple example we just free the resources
		// returned by getaddrinfo and print an error message
		//freeaddrinfo(result);
	}


private:
	SOCKET handle_; // Socket handle factory
	INET_Addr sock_addr_; // Address
};
